//
//  ByDoubleBallListVC.m
//  caipiao_ios
//
//  Created by mc on 2018/7/18.
//  Copyright © 2018年 ZhangZhanbin. All rights reserved.
//

#import "ByDoubleBallListVC.h"
#import "BySuperLottoListHeadView.h"
#import "BySuperLottoListBottomView.h"
#import "BySuperLottoListCirclesView.h"
#import "BySuperLottoFooterVIew.h"
#import "BySuperLottoAddMinusView.h"

@interface ByDoubleBallListVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) BySuperLottoFooterVIew *footView;
@property (nonatomic, strong) BySuperLottoListBottomView *bottomView;


@property (nonatomic, strong) ByPayBombView *payBombView;

@property (nonatomic, strong) ByNetModel *orderModel;

@end

@implementation ByDoubleBallListVC

- (NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray arrayWithCapacity:1];
    }
    return _dataArray;
}

- (ByPayBombView *)payBombView{
    if (_payBombView == nil) {
        _payBombView = [[ByPayBombView alloc] init];
        
        __weak typeof(self) weakSelf = self;
        _payBombView.sureBlock = ^(){
            
            
            [weakSelf.payBombView remove];
            weakSelf.payBombView = nil;
            [weakSelf by_normalPopVC:@""];
        
        };
        
        _payBombView.otherSureBlock = ^(NSString *str,NSInteger type){
            
            [weakSelf.payBombView remove];
            weakSelf.payBombView = nil;
            
            if (type == 1) {
                ByWebViewController *vc = [[ByWebViewController alloc] initWithTotalUrlString:str];
                vc.titleString = @"支付宝支付";
                [weakSelf by_normalPush:vc hasNavi:YES];
            }else{
                ByWechatPayQrView *vc = [[ByWechatPayQrView alloc] init];
                vc.title = @"微信支付";
                vc.str = str;
                [weakSelf by_normalPush:vc hasNavi:YES];
            }
            
        };
        
        _payBombView.selectBlock = ^(NSInteger index){
          
        };
    }
    return _payBombView;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.dataArray = BY_APPDELEGATE.selectedArray;
    
    
    [self addLeftBackBarButtonItem];
    self.title = @"投注单";
    [self initViews];
    
    if (self.dataArray.count == 0) {
        self.footView.hidden = YES;
    }
    
    // Do any additional setup after loading the view.
}


- (void)initViews{
    
    BySuperLottoListHeadView *headView = [[BySuperLottoListHeadView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 100)];
    [self.view addSubview:headView];
    
    if (self.newestModel.phaseno.length == 0){
        
        headView.topLabel.hidden = YES;
        
    }else{
         headView.topLabel.text =  [NSString stringWithFormat:@"第%@期 %@截止投注",self.newestModel.phaseno, [NSDate getDateStringFromeNumber:[NSNumber numberWithInteger:self.newestModel.localendtime.integerValue]]];
    }
    
    
    headView.leftBlock = ^(){
        NSMutableArray *selectedArray = [ByLotteryAlgorithmHandle getRandomDoubleBallSelectedDataTwoArray];
        ByNetModel *netModel = [[ByNetModel alloc] init];
        netModel.count = 1;
        netModel.type = 0;
        netModel.dataArray = [selectedArray copy];
        [self.dataArray addObject:netModel];
        [self.tableView reloadData];
        [self updateBottomState];
        [ByCoreToolAlert showSuccessWithText:@"添加成功"];
    };
    headView.centerBlock = ^(){
        
        NSMutableArray *tempArray = [NSMutableArray arrayWithCapacity:1];
        for (int i = 0; i < 5; i++) {
            ByNetModel *netModel = [[ByNetModel alloc] init];
            netModel.count = 1;
            netModel.type = 0;
            NSMutableArray *selectedArray = [ByLotteryAlgorithmHandle getRandomDoubleBallSelectedDataTwoArray];
            netModel.dataArray = [selectedArray copy];
            [tempArray addObject:netModel];
        }
        [self.dataArray addObjectsFromArray:[tempArray copy]];
        [self.tableView reloadData];
        [self updateBottomState];
        [ByCoreToolAlert showSuccessWithText:@"添加成功"];
    };
    
    headView.rightBlock = ^(){
        BY_APPDELEGATE.selectedArray = self.dataArray;
        [self leftItemsAction:0];
    };
    
    
    self.view.backgroundColor = BY_BACKGROUND_COLOR;
    self.tableView = [[UITableView alloc] init];
    self.tableView.backgroundColor = BY_BACKGROUND_COLOR;
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(0);
        make.right.equalTo(self.view).offset(0);
        make.top.equalTo(headView.mas_bottom).offset(10);
       
        if (@available(ios 11.0,*)) {
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(-150);
        } else {
            make.bottom.equalTo(self.view).offset(-150);
        }
    }];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    BySuperLottoFooterVIew *footView = [[BySuperLottoFooterVIew alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
    self.tableView.tableFooterView = footView;
    footView.deleteBlock = ^(){
        [self.dataArray removeAllObjects];
        [self.tableView reloadData];
        if (self.dataArray.count == 0) {
            self.footView.hidden = YES;
        }
        
         [self updateBottomState];
    };
    self.footView = footView;
    if (self.dataArray.count == 0) {
        self.footView.hidden = YES;
    }
    
    BySuperLottoListBottomView *bottomView = [[BySuperLottoListBottomView alloc] init];
    [self.view addSubview:bottomView];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(0);
        make.right.equalTo(self.view).offset(0);
        make.height.mas_equalTo(@150);
        make.top.equalTo(self.tableView.mas_bottom).offset(0);
    }];
    self.bottomView = bottomView;
    
    bottomView.addMinusView1.updateBlock = ^(){
        [self updateBottomState];
    };
    bottomView.addMinusView2.updateBlock = ^(){
        [self updateBottomState];
    };
    
    __weak typeof(BySuperLottoListBottomView *) weakView = bottomView;
    bottomView.sureBlock = ^(){
        if (self.dataArray.count == 0) {
            return ;
        }
        ByNetModel *netModel = [[ByNetModel alloc] init];
        netModel.multiple = weakView.addMinusView2.countLabel.text;
        netModel.push_number = weakView.addMinusView1.countLabel.text;
        if (weakView.selectBtn.selected) {
            netModel.is_rand = @"1";
        }
        
        netModel.numArray = [ByLotteryAlgorithmHandle getColorBallNumArrayWithDataArray:self.dataArray];
        
        
        [ByCoreToolAlert showLoadind:@"投注处理中" hasMasker:YES];
        [ByNumberApi getColorBallCreateOrder:netModel success:^(ByNetBaseResult *result) {
            [ByCoreToolAlert hideHud];
            NSLog(@"大乐透投注 = %@", result.data);
            self.orderModel = [[ByNetModel alloc] initContentWithDic:result.data[@"data"]];
            self.payBombView.moneyLabel.text = [NSString stringWithFormat:@"%@元", self.orderModel.amount];
            self.payBombView.orderModel = self.orderModel;
            [self.payBombView show];
            
        
        } failure:^(ByNetBaseResult *result) {
            [ByCoreToolAlert showOnlyText:result.msg];
        }];
        
    };
    
    bottomView.ruleBlock = ^(){
        ByWebViewController *vc = [[ByWebViewController alloc] initWithTotalUrlString:[NSString stringWithFormat:@"%@/Wanfajiesao/jiesao?type=1001",BOYE_WEB_BASE_URL]];
        vc.titleString = @"双色球玩法说明";
        [self by_normalPush:vc hasNavi:YES];
    };
    
     [self updateBottomState];
}


- (void)updateBottomState{
    
    if (self.dataArray.count == 0) {
        self.bottomView.addMinusView1.countLabel.text = @"1";
        self.bottomView.addMinusView2.countLabel.text = @"1";
    }
    
    NSInteger count = 0;
    for (int i = 0; i < self.dataArray.count; i++) {
        ByNetModel *netModel = [self.dataArray objectAtIndex:i];
        count = count + netModel.count;
    }
    
    self.bottomView.moneyLabel.text = [NSString stringWithFormat:@"%.f元", self.bottomView.addMinusView1.countLabel.text.integerValue * self.bottomView.addMinusView2.countLabel.text.integerValue * count * 2.0];
    self.bottomView.otherLabel.text = [NSString stringWithFormat:@"%ld注 %@倍 %@期", count,self.bottomView.addMinusView2.countLabel.text, self.bottomView.addMinusView1.countLabel.text];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        
        UILabel *line = [[UILabel alloc] init];
        [cell addSubview:line];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(cell).offset(0);
            make.right.equalTo(cell).offset(0);
            make.bottom.equalTo(cell).offset(0);
            make.height.mas_equalTo(@1);
        }];
        line.backgroundColor = BY_LINE_COLOR;
    }
    
    for (UIView *view in cell.contentView.subviews) {
        [view removeFromSuperview];
    }
    
    cell.contentView.backgroundColor = BY_BACKGROUND_COLOR;
    
    UIView *backgroundView = [[UIView alloc] init];
    [cell.contentView addSubview:backgroundView];
    [backgroundView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(cell.contentView).offset(10);
        make.right.equalTo(cell.contentView).offset(-10);
        make.top.equalTo(cell.contentView).offset(0);
        make.bottom.equalTo(cell.contentView).offset(-1);
    }];
    backgroundView.backgroundColor = [UIColor whiteColor];
    
    UIButton *deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backgroundView addSubview:deleteBtn];
    [deleteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(backgroundView).offset(10);
        make.top.equalTo(backgroundView).offset(20);
        make.size.mas_equalTo(CGSizeMake(15, 15));
    }];
    [deleteBtn setImage:[UIImage imageNamed:@"guanbi11111"] forState:UIControlStateNormal];
    deleteBtn.tag = 100 + indexPath.row;
    [deleteBtn addTarget:self action:@selector(deleteBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    
    UIImageView *arrowView = [[UIImageView alloc] init];
    [backgroundView addSubview:arrowView];
    [arrowView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(backgroundView).offset(-10);
        make.top.equalTo(deleteBtn.mas_top).offset(0);
        make.size.mas_equalTo(CGSizeMake(15, 15));
    }];
    arrowView.image = [UIImage imageNamed:@"youjiantou1111"];
    
    ByNetModel *netModel = [self.dataArray objectAtIndex:indexPath.row];
    NSMutableArray *dataArray = [netModel.dataArray copy];
    
    CGFloat top = 15;
    for (int i = 0; i < dataArray.count; i++) {
        NSMutableArray *smallArray = [dataArray objectAtIndex:i];
        BySuperLottoListCirclesView *circlesView = [[BySuperLottoListCirclesView alloc] init];
        [backgroundView addSubview:circlesView];
        
        [circlesView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(deleteBtn.mas_right).offset(10);
            make.right.equalTo(arrowView.mas_left).offset(0);
            make.top.equalTo(backgroundView).offset(top);
            make.height.mas_equalTo(@([BySuperLottoListCirclesView getHeightWithDataArray:smallArray]));
        }];
        
        top = top + [BySuperLottoListCirclesView getHeightWithDataArray:smallArray];
        if (dataArray.count == 2) {
            
            if (i == 0) {
                circlesView.titleLabel.text = @"红球:";
                circlesView.themeColor = BY_THEME_COLOR;
            }else if (i == 1){
                circlesView.titleLabel.text = @"篮球:";
                circlesView.themeColor = BY_Blue_COLOR;
            }
            
        }else if (dataArray.count == 3){
            
            if (i == 0) {
                circlesView.titleLabel.text = @"红(胆):";
                circlesView.themeColor = BY_THEME_COLOR;
            }else if (i == 1){
                circlesView.titleLabel.text = @"红(拖):";
                circlesView.themeColor = BY_THEME_COLOR;
            }else if (i == 2){
                circlesView.titleLabel.text = @"蓝球:";
                circlesView.themeColor = BY_Blue_COLOR;
            }
            
        }
        
        circlesView.dataArray = smallArray;
    }
    
    UILabel *valueLabel = [[UILabel alloc] init];
    [cell.contentView addSubview:valueLabel];
    [valueLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(backgroundView).offset(10);
        make.right.equalTo(backgroundView).offset(-10);
        make.bottom.equalTo(backgroundView).offset(-5);
        make.height.mas_equalTo(@20);
    }];
    
    NSString *type = @"";
    if (netModel.type == 0) {
        type = @"单式";
    }else if (netModel.type == 1){
        type = @"红球复式";
    }else if (netModel.type == 2){
        type = @"蓝球复式";
    }else if (netModel.type == 3){
        type = @"全复式";
    }else if (netModel.type == 4){
        type = @"胆拖";
    }
    
    valueLabel.text= [NSString stringWithFormat:@"%@ %ld注 %.f元",type,netModel.count,netModel.count * 2.0];
    valueLabel.textColor = [UIColor lightGrayColor];
    valueLabel.textAlignment = NSTextAlignmentCenter;
    valueLabel.font = FONT(12);
    
    return cell;
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    ByNetModel *netModel = [self.dataArray objectAtIndex:indexPath.row];
    NSMutableArray *dataArray = [netModel.dataArray copy];
    CGFloat height = 15;
    for (int i = 0; i < dataArray.count; i++) {
        NSMutableArray *smallArray = [dataArray objectAtIndex:i];
        height = height + [BySuperLottoListCirclesView getHeightWithDataArray:smallArray];
    }
    
    return  height + 30;
}


- (void)deleteBtn:(UIButton *)btn{
    NSInteger index = btn.tag  - 100;
    [self.dataArray removeObjectAtIndex:index];
    [self.tableView reloadData];
    [self updateBottomState];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
